package com.sky.business.sys.handler.cmcc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.CameraConfig;
import com.sky.business.sys.domain.SystemConfig;
import com.sky.business.sys.handler.MqttEventHandler;
import com.sky.business.sys.service.CameraConfigService;
import com.sky.business.sys.service.SystemConfigService;
import com.sky.business.sys.util.MQTTClientUtils;
import com.sky.common.config.CacheConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.SimpleTimeZone;

/**
 * 终端请求转发处理器
 *
 */
@Slf4j
@Component
public class ForwardToEndpointEventHandler implements MqttEventHandler {

    @Autowired
    private CameraConfigService cameraConfigService;

    @Autowired
    private SystemConfigService systemConfigService;

    public static ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));


    @Override
    public boolean match(String topic, String msg,String event) {
        return "SetHome".equals(event) || "MoveHome".equals(event) ||
                "DetectToggle".equals(event) || "TrackToggle".equals(event) ||
                "AbsMoveByAngle".equals(event) || "AbsMove".equals(event) || "isDetect".equals(event) ||
                "IsTrack".equals(event) || "TargetRelease".equals(event) || "CameraStatus".equals(event);
    }


    @Override
    public void handle(String topic, String msg) throws Exception {
        Map<?, ?> map = objectMapper.readValue(msg, Map.class);
        Map<String, Object> metadata = (Map<String, Object>) map.get("metadata");
        String deviceId = String.valueOf(metadata.get("deviceId"));
        CameraConfig cameraConfig = cameraConfigService.findByDeviceId(deviceId);
        if(cameraConfig==null){
            SystemConfig systemConfig = systemConfigService.getSystemConfig();
            metadata.put("codeStatus",CacheConstants.CODE_STATUS_ERROR);
            metadata.put("message","设备不存在");
            String newMsg = objectMapper.writeValueAsString(map);
            MQTTClientUtils.publish(MQTTClientUtils.CMCC_MQTT_CLIENT,systemConfig.getCmccReportingTopic(), CacheConstants.DEFAULT_QOS,newMsg);
        }else {
            MQTTClientUtils.publish(MQTTClientUtils.LOCAL_MQTT_CLIENT, cameraConfig.getDispatcherTopic(), CacheConstants.DEFAULT_QOS, msg);
        }
    }


}
